{% extends "admin/base.html" %}

{% block title %}题目设计{% endblock %}

{% block extra_css %}
<style>
.question-card {
    border: 1px solid #dee2e6;
    border-radius: 0.375rem;
    margin-bottom: 1.5rem;
    transition: box-shadow 0.3s ease;
}

.question-card:hover {
    box-shadow: 0 0.25rem 0.5rem rgba(0, 0, 0, 0.1);
}

.question-header {
    background-color: #f8f9fa;
    padding: 1rem;
    border-bottom: 1px solid #dee2e6;
    border-radius: 0.375rem 0.375rem 0 0;
}

.question-body {
    padding: 1.5rem;
}

.option-item {
    background-color: #f8f9fa;
    border: 1px solid #dee2e6;
    border-radius: 0.25rem;
    padding: 0.75rem;
    margin-bottom: 0.5rem;
}

.add-question-btn {
    border: 2px dashed #007bff;
    background-color: #f8f9fa;
    color: #007bff;
    padding: 2rem;
    text-align: center;
    border-radius: 0.375rem;
    cursor: pointer;
    transition: all 0.3s ease;
}

.add-question-btn:hover {
    background-color: #e3f2fd;
    border-color: #0056b3;
}

.toolbar {
    background-color: #ffffff;
    border: 1px solid #dee2e6;
    border-radius: 0.375rem;
    padding: 1rem;
    margin-bottom: 1.5rem;
    box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
}
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 页面标题 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h1 class="h3 mb-0">题目设计</h1>
            <p class="text-muted mb-0" id="scaleTitle">量表题目设计</p>
        </div>
        <div>
            <a href="/admin/scales" class="btn btn-outline-secondary me-2">
                <i class="bi bi-arrow-left me-1"></i>返回列表
            </a>
            <button class="btn btn-outline-primary me-2" onclick="previewScale()">
                <i class="bi bi-eye me-1"></i>预览量表
            </button>
        </div>
    </div>

    <input type="hidden" id="scaleId" value="">

    <!-- 工具栏 -->
    <div class="toolbar">
        <div class="d-flex justify-content-between align-items-center">
            <div>
                <span class="text-muted me-3">共 <strong id="questionCount">0</strong> 题</span>
                <small class="badge bg-info">美化版 v2.2</small>
                <small class="badge bg-secondary ms-1" id="debugInfo">调试模式</small>
            </div>
            <div>
                <button class="btn btn-success me-2" onclick="saveAllQuestions()">
                    <i class="bi bi-cloud-upload me-1"></i>保存到数据库
                </button>
                <button class="btn btn-outline-primary" onclick="addQuestion()">
                    <i class="bi bi-plus-circle me-1"></i>添加题目
                </button>
                <button class="btn btn-outline-info btn-sm" onclick="debugQuestions()">
                    <i class="bi bi-bug me-1"></i>调试
                </button>
            </div>
        </div>
    </div>

    <!-- 题目列表 -->
    <div id="questionsContainer">
        <!-- 空状态提示 -->
        <div id="emptyState" class="text-center py-5">
            <i class="bi bi-question-circle fs-1 text-muted mb-3"></i>
            <h5 class="text-muted">还没有题目</h5>
            <p class="text-muted mb-3">开始创建第一个题目</p>
            <button class="btn btn-primary" onclick="addQuestion()">
                <i class="bi bi-plus-circle me-1"></i>添加第一个题目
            </button>
        </div>
    </div>

    <!-- 添加题目按钮（当有题目时显示） -->
    <div id="addQuestionArea" class="add-question-btn" onclick="addQuestion()" style="display: none;">
        <i class="bi bi-plus-circle fs-1 mb-2"></i>
        <h5>添加新题目</h5>
        <p class="mb-0 text-muted">点击添加更多题目</p>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
console.log('🚀 新版题目设计页面已加载 - v2.2 (美化版) ' + new Date().toISOString());
let questions = [];

document.addEventListener('DOMContentLoaded', function() {
    initializePage();
});

function initializePage() {
    // 检查管理员认证
    const adminToken = localStorage.getItem('adminToken');
    if (!adminToken) {
        showAlert('请先登录管理员账户', 'error');
        setTimeout(() => window.location.href = '/admin-portal', 2000);
        return;
    }
    
    // 获取量表ID
    const urlParams = new URLSearchParams(window.location.search);
    const scaleId = urlParams.get('id');
    
    if (!scaleId) {
        showAlert('缺少量表ID参数', 'error');
        setTimeout(() => window.location.href = '/admin/scales', 2000);
        return;
    }
    
    document.getElementById('scaleId').value = scaleId;
    loadScaleData(scaleId);
}

function loadScaleData(scaleId) {
    fetch(`/api/admin/scales/${scaleId}`, {
        headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('adminToken')
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            document.getElementById('scaleTitle').textContent = `${data.data.title} - 题目设计`;
            questions = data.data.questions || [];
            renderAllQuestions();
        } else {
            showAlert('加载量表失败: ' + data.message, 'error');
        }
    })
    .catch(error => {
        console.error('加载量表失败:', error);
        showAlert('加载量表失败', 'error');
    });
}

function renderAllQuestions() {
    const container = document.getElementById('questionsContainer');
    const emptyState = document.getElementById('emptyState');
    const addArea = document.getElementById('addQuestionArea');
    
    // 更新题目计数
    document.getElementById('questionCount').textContent = questions.length;
    
    if (questions.length === 0) {
        // 显示空状态
        if (emptyState) emptyState.style.display = 'block';
        if (addArea) addArea.style.display = 'none';
        
        // 清空容器中的题目，但保留emptyState
        const existingQuestions = container.querySelectorAll('.question-card');
        existingQuestions.forEach(card => card.remove());
        return;
    }
    
    // 隐藏空状态，显示添加按钮
    if (emptyState) emptyState.style.display = 'none';
    if (addArea) addArea.style.display = 'block';
    
    // 清空现有题目
    const existingQuestions = container.querySelectorAll('.question-card');
    existingQuestions.forEach(card => card.remove());
    
    // 创建题目HTML
    const questionsHTML = questions.map((question, index) => 
        createQuestionCard(question, index)
    ).join('');
    
    // 在emptyState之后插入题目
    if (emptyState) {
        emptyState.insertAdjacentHTML('afterend', questionsHTML);
    } else {
        container.insertAdjacentHTML('beforeend', questionsHTML);
    }
}

function createQuestionCard(question, index) {
    const questionNumber = index + 1;
    const questionTypes = {
        'single': '单选题',
        'multiple': '多选题',
        'scale': '量表题',
        'text': '文本题',
        'boolean': '是非题'
    };
    
    return `
        <div class="question-card" data-index="${index}">
            <div class="question-header">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <span class="badge bg-primary me-2">第${questionNumber}题</span>
                        <span class="badge bg-info">${questionTypes[question.question_type] || '未知'}</span>
                        ${question.is_required ? '<span class="badge bg-warning ms-1">必答</span>' : ''}
                    </div>
                    <div class="btn-group btn-group-sm">
                        <button class="btn btn-outline-primary" onclick="moveQuestion(${index}, -1)" ${index === 0 ? 'disabled' : ''}>
                            <i class="bi bi-arrow-up"></i>
                        </button>
                        <button class="btn btn-outline-primary" onclick="moveQuestion(${index}, 1)" ${index === questions.length - 1 ? 'disabled' : ''}>
                            <i class="bi bi-arrow-down"></i>
                        </button>
                        <button class="btn btn-outline-danger" onclick="deleteQuestion(${index})">
                            <i class="bi bi-trash"></i>
                        </button>
                    </div>
                </div>
            </div>
            <div class="question-body">
                <!-- 题目内容 -->
                <div class="mb-3">
                    <label class="form-label fw-bold">题目内容</label>
                    <textarea class="form-control" rows="3" placeholder="请输入题目内容..." 
                              onchange="updateQuestion(${index}, 'question_text', this.value)">${question.question_text || ''}</textarea>
                </div>
                
                <!-- 题目设置 -->
                <div class="row mb-3">
                    <div class="col-md-6">
                        <label class="form-label">题目类型</label>
                        <select class="form-select" onchange="updateQuestionType(${index}, this.value)">
                            <option value="single" ${question.question_type === 'single' ? 'selected' : ''}>单选题</option>
                            <option value="multiple" ${question.question_type === 'multiple' ? 'selected' : ''}>多选题</option>
                            <option value="scale" ${question.question_type === 'scale' ? 'selected' : ''}>量表题</option>
                            <option value="text" ${question.question_type === 'text' ? 'selected' : ''}>文本题</option>
                            <option value="boolean" ${question.question_type === 'boolean' ? 'selected' : ''}>是非题</option>
                        </select>
                    </div>
                    <div class="col-md-6">
                        <div class="form-check mt-4">
                            <input class="form-check-input" type="checkbox" ${question.is_required ? 'checked' : ''}
                                   onchange="updateQuestion(${index}, 'is_required', this.checked)">
                            <label class="form-check-label">必答题目</label>
                        </div>
                    </div>
                </div>
                
                <!-- 选项设置 -->
                ${question.question_type !== 'text' ? createOptionsSection(question, index) : ''}
            </div>
        </div>
    `;
}

function createOptionsSection(question, questionIndex) {
    const options = question.options || [];
    
    const optionsHTML = options.map((option, optionIndex) => `
        <div class="option-item">
            <div class="row g-2 align-items-center">
                <div class="col-md-2">
                    <input type="text" class="form-control form-control-sm" 
                           value="${option.option_key || ''}" placeholder="标识"
                           onchange="updateOption(${questionIndex}, ${optionIndex}, 'option_key', this.value)">
                </div>
                <div class="col-md-6">
                    <input type="text" class="form-control form-control-sm" 
                           value="${option.option_text || ''}" placeholder="选项内容"
                           onchange="updateOption(${questionIndex}, ${optionIndex}, 'option_text', this.value)">
                </div>
                <div class="col-md-2">
                    <input type="number" class="form-control form-control-sm" 
                           value="${option.option_value || 0}" placeholder="分值"
                           onchange="updateOption(${questionIndex}, ${optionIndex}, 'option_value', parseInt(this.value) || 0)">
                </div>
                <div class="col-md-2">
                    <button class="btn btn-outline-danger btn-sm" onclick="removeOption(${questionIndex}, ${optionIndex})">
                        <i class="bi bi-trash"></i>
                    </button>
                </div>
            </div>
        </div>
    `).join('');
    
    return `
        <div class="mb-3">
            <div class="d-flex justify-content-between align-items-center mb-2">
                <label class="form-label fw-bold">选项设置</label>
                <button class="btn btn-outline-primary btn-sm" onclick="addOption(${questionIndex})">
                    <i class="bi bi-plus"></i> 添加选项
                </button>
            </div>
            <div id="options-${questionIndex}">
                ${optionsHTML}
            </div>
        </div>
    `;
}

function addQuestion() {
    const newQuestion = {
        question_number: questions.length + 1,
        question_text: `第 ${questions.length + 1} 题（请编辑题目内容）`,
        question_type: 'single',
        is_required: true,
        options: [
            { option_key: 'A', option_text: '选项A', option_value: 1, sort_order: 0 },
            { option_key: 'B', option_text: '选项B', option_value: 2, sort_order: 1 }
        ]
    };
    
    questions.push(newQuestion);
    
    console.log('添加新题目:', newQuestion);
    console.log('当前题目总数:', questions.length);
    
    // 完全重新渲染（确保正确显示）
    renderAllQuestions();
    
    // 延迟更长时间确保DOM完全更新
    setTimeout(() => {
        // 更新题目计数
        document.getElementById('questionCount').textContent = questions.length;
        
        // 找到新添加的题目卡片
        const newCard = document.querySelector(`[data-index="${questions.length - 1}"]`);
        console.log('查找新题目卡片:', newCard);
        
        if (newCard) {
            // 滚动到新题目
            newCard.scrollIntoView({ behavior: 'smooth', block: 'center' });
            
            // 查找题目内容输入框
            const textarea = newCard.querySelector('textarea');
            console.log('查找textarea:', textarea);
            
            if (textarea) {
                // 确保焦点设置成功
                setTimeout(() => {
                    textarea.focus();
                    textarea.select(); // 选中默认文字
                    console.log('已设置焦点到新题目');
                }, 100);
            } else {
                console.error('未找到新题目的textarea元素');
            }
        } else {
            console.error('未找到新添加的题目卡片');
        }
    }, 300);
    
    showAlert(`已添加第 ${questions.length} 题，请编辑题目内容`, 'success', 3000);
}

function deleteQuestion(index) {
    showConfirmModal(
        '确认删除题目',
        `确定要删除第 ${index + 1} 题吗？此操作不可撤销。`,
        'danger',
        function() {
            questions.splice(index, 1);
            // 重新编号
            questions.forEach((q, i) => q.question_number = i + 1);
            renderAllQuestions();
            showAlert('题目删除成功', 'success', 2500);
        }
    );
}

function moveQuestion(index, direction) {
    const newIndex = index + direction;
    if (newIndex < 0 || newIndex >= questions.length) return;
    
    // 交换位置
    [questions[index], questions[newIndex]] = [questions[newIndex], questions[index]];
    
    // 重新编号
    questions.forEach((q, i) => q.question_number = i + 1);
    
    renderAllQuestions();
    showAlert('题目顺序已调整', 'success');
}

function updateQuestion(index, field, value) {
    if (questions[index]) {
        questions[index][field] = value;
        // 不需要重新渲染，只更新内存中的数据
        console.log(`更新题目 ${index + 1} 的 ${field}:`, value);
    }
}

function updateQuestionType(index, newType) {
    if (questions[index]) {
        questions[index].question_type = newType;
        
        // 根据题目类型设置默认选项
        if (newType === 'text') {
            questions[index].options = [];
        } else if (newType === 'boolean') {
            questions[index].options = [
                { option_key: 'A', option_text: '是', option_value: 1, sort_order: 0 },
                { option_key: 'B', option_text: '否', option_value: 0, sort_order: 1 }
            ];
        } else if (newType === 'scale') {
            questions[index].options = [
                { option_key: 'A', option_text: '完全不符合', option_value: 1, sort_order: 0 },
                { option_key: 'B', option_text: '不符合', option_value: 2, sort_order: 1 },
                { option_key: 'C', option_text: '一般', option_value: 3, sort_order: 2 },
                { option_key: 'D', option_text: '符合', option_value: 4, sort_order: 3 },
                { option_key: 'E', option_text: '完全符合', option_value: 5, sort_order: 4 }
            ];
        } else if (!questions[index].options || questions[index].options.length === 0) {
            questions[index].options = [
                { option_key: 'A', option_text: '选项A', option_value: 1, sort_order: 0 },
                { option_key: 'B', option_text: '选项B', option_value: 2, sort_order: 1 }
            ];
        }
        
        // 只更新特定题目的选项部分，避免重新渲染整个列表
        updateQuestionOptions(index);
        console.log(`题目 ${index + 1} 类型已更改为: ${newType}`);
    }
}

function updateQuestionOptions(index) {
    // 找到特定题目的选项容器
    const questionCard = document.querySelector(`[data-index="${index}"]`);
    if (!questionCard) return;
    
    const question = questions[index];
    const optionsContainer = questionCard.querySelector('.question-body');
    
    if (!optionsContainer) return;
    
    // 移除现有的选项设置部分
    const existingOptionsSection = optionsContainer.querySelector('.mb-3:last-child');
    if (existingOptionsSection && existingOptionsSection.innerHTML.includes('选项设置')) {
        existingOptionsSection.remove();
    }
    
    // 如果不是文本题，添加新的选项设置
    if (question.question_type !== 'text') {
        const optionsHTML = createOptionsSection(question, index);
        optionsContainer.insertAdjacentHTML('beforeend', optionsHTML);
    }
}

function updateOption(questionIndex, optionIndex, field, value) {
    if (questions[questionIndex] && questions[questionIndex].options[optionIndex]) {
        questions[questionIndex].options[optionIndex][field] = value;
    }
}

function addOption(questionIndex) {
    if (questions[questionIndex]) {
        const options = questions[questionIndex].options || [];
        const nextKey = String.fromCharCode(65 + options.length);
        
        options.push({
            option_key: nextKey,
            option_text: `选项${nextKey}`,
            option_value: options.length + 1,
            sort_order: options.length
        });
        
        questions[questionIndex].options = options;
        
        // 只更新特定题目的选项部分
        updateQuestionOptions(questionIndex);
        console.log(`为题目 ${questionIndex + 1} 添加了选项 ${nextKey}`);
    }
}

function removeOption(questionIndex, optionIndex) {
    if (questions[questionIndex] && questions[questionIndex].options) {
        if (questions[questionIndex].options.length <= 1) {
            showAlert('至少需要保留一个选项', 'warning');
            return;
        }
        
        questions[questionIndex].options.splice(optionIndex, 1);
        // 重新编号选项
        questions[questionIndex].options.forEach((opt, i) => {
            opt.sort_order = i;
            if (!opt.option_key) {
                opt.option_key = String.fromCharCode(65 + i);
            }
        });
        
        // 只更新特定题目的选项部分
        updateQuestionOptions(questionIndex);
        console.log(`从题目 ${questionIndex + 1} 移除了选项`);
    }
}

function saveAllQuestions() {
    console.log('🔄 开始保存题目到数据库...');
    
    const scaleId = document.getElementById('scaleId').value;
    console.log('量表ID:', scaleId);
    console.log('当前题目数组:', questions);
    
    if (!scaleId) {
        console.error('量表ID缺失');
        showAlert('量表ID缺失', 'error');
        return;
    }
    
    if (questions.length === 0) {
        showAlert('请至少添加一个题目', 'warning');
        return;
    }
    
    // 验证题目完整性
    for (let i = 0; i < questions.length; i++) {
        const question = questions[i];
        
        if (!question.question_text || question.question_text.trim() === '') {
            showAlert(`第 ${i + 1} 题的内容不能为空`, 'warning');
            return;
        }
        
        if (question.question_type !== 'text') {
            if (!question.options || question.options.length === 0) {
                showAlert(`第 ${i + 1} 题缺少选项`, 'warning');
                return;
            }
            
            for (let j = 0; j < question.options.length; j++) {
                if (!question.options[j].option_text || question.options[j].option_text.trim() === '') {
                    showAlert(`第 ${i + 1} 题的选项 ${j + 1} 内容不能为空`, 'warning');
                    return;
                }
            }
        }
    }
    
    // 显示保存状态
    const saveBtn = document.querySelector('button[onclick="saveAllQuestions()"]');
    if (!saveBtn) {
        console.error('未找到保存按钮');
        showAlert('保存按钮未找到，请刷新页面重试', 'error');
        return;
    }
    
    console.log('找到保存按钮:', saveBtn);
    const originalText = saveBtn.innerHTML;
    saveBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>保存中...';
    saveBtn.disabled = true;
    
    console.log('📡 发送保存请求到服务器...');
    
    fetch(`/api/admin/scales/${scaleId}/questions`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + localStorage.getItem('adminToken')
        },
        body: JSON.stringify({ questions: questions })
    })
    .then(response => {
        console.log('📥 收到服务器响应:', response.status);
        return response.json();
    })
    .then(data => {
        console.log('📋 服务器返回数据:', data);
        if (data.success) {
            console.log('✅ 保存成功');
            showSuccessToast('题目保存成功', `已成功保存 ${questions.length} 个题目到数据库！`);
        } else {
            console.error('❌ 保存失败:', data.message);
            showAlert('保存失败: ' + data.message, 'error');
        }
    })
    .catch(error => {
        console.error('❌ 网络错误:', error);
        showAlert('保存失败，请检查网络连接', 'error');
    })
    .finally(() => {
        console.log('📝 保存操作完成，恢复按钮状态');
        if (saveBtn) {
            saveBtn.innerHTML = originalText;
            saveBtn.disabled = false;
        }
    });
}

function previewScale() {
    const scaleId = document.getElementById('scaleId').value;
    if (scaleId) {
        window.open(`/scales/${scaleId}/preview`, '_blank');
    }
}

function debugQuestions() {
    console.log('=== 题目调试信息 ===');
    console.log('当前题目数组:', questions);
    console.log('题目总数:', questions.length);
    console.log('DOM中的题目卡片数:', document.querySelectorAll('.question-card').length);
    console.log('emptyState显示状态:', document.getElementById('emptyState')?.style.display);
    console.log('addArea显示状态:', document.getElementById('addQuestionArea')?.style.display);
    
    // 检查保存按钮状态
    const saveBtn = document.querySelector('button[onclick="saveAllQuestions()"]');
    console.log('保存按钮:', saveBtn);
    console.log('保存按钮是否禁用:', saveBtn ? saveBtn.disabled : '未找到');
    
    // 检查量表ID
    const scaleId = document.getElementById('scaleId')?.value;
    console.log('量表ID:', scaleId);
    
    // 检查管理员Token
    const adminToken = localStorage.getItem('adminToken');
    console.log('管理员Token存在:', !!adminToken);
    
    // 显示详细题目信息
    questions.forEach((q, i) => {
        console.log(`题目 ${i + 1}:`, {
            question_text: q.question_text,
            question_type: q.question_type,
            options_count: q.options?.length || 0,
            is_required: q.is_required
        });
    });
    
    showAlert(`调试信息已输出到控制台。共 ${questions.length} 题`, 'info');
}

function showAlert(message, type = 'info', duration = 4000) {
    // 创建Toast容器（如果不存在）
    let toastContainer = document.getElementById('toast-container');
    if (!toastContainer) {
        toastContainer = document.createElement('div');
        toastContainer.id = 'toast-container';
        toastContainer.className = 'toast-container position-fixed top-0 end-0 p-3';
        toastContainer.style.zIndex = '9999';
        document.body.appendChild(toastContainer);
    }
    
    // 确定图标和样式
    const icons = {
        'success': { icon: 'bi-check-circle-fill', bgClass: 'bg-success', textClass: 'text-white' },
        'error': { icon: 'bi-exclamation-triangle-fill', bgClass: 'bg-danger', textClass: 'text-white' },
        'warning': { icon: 'bi-exclamation-circle-fill', bgClass: 'bg-warning', textClass: 'text-dark' },
        'info': { icon: 'bi-info-circle-fill', bgClass: 'bg-info', textClass: 'text-white' }
    };
    
    const config = icons[type] || icons.info;
    const toastId = 'toast-' + Date.now();
    
    // 创建Toast HTML
    const toastHTML = `
        <div id="${toastId}" class="toast ${config.bgClass} ${config.textClass} border-0 shadow-lg" role="alert" aria-live="assertive" aria-atomic="true" data-bs-delay="${duration}">
            <div class="d-flex align-items-center p-3">
                <i class="bi ${config.icon} fs-5 me-3"></i>
                <div class="flex-grow-1 fw-medium">
                    ${message}
                </div>
                <button type="button" class="btn-close ${config.textClass === 'text-white' ? 'btn-close-white' : ''} ms-2" data-bs-dismiss="toast" aria-label="Close"></button>
            </div>
        </div>
    `;
    
    // 添加到容器
    toastContainer.insertAdjacentHTML('afterbegin', toastHTML);
    
    // 初始化并显示Toast
    const toastElement = document.getElementById(toastId);
    const toast = new bootstrap.Toast(toastElement, {
        animation: true,
        autohide: true,
        delay: duration
    });
    
    // 显示Toast
    toast.show();
    
    // 自动移除DOM元素
    toastElement.addEventListener('hidden.bs.toast', function() {
        toastElement.remove();
        
        // 如果容器为空，也移除容器
        if (toastContainer.children.length === 0) {
            toastContainer.remove();
        }
    });
    
    return toast;
}

// 美观的确认对话框
function showConfirmModal(title, message, type = 'primary', onConfirm = null, onCancel = null) {
    // 确定按钮样式
    const buttonConfig = {
        'danger': { class: 'btn-danger', icon: 'bi-trash', text: '删除' },
        'warning': { class: 'btn-warning', icon: 'bi-exclamation-triangle', text: '确认' },
        'primary': { class: 'btn-primary', icon: 'bi-check', text: '确认' },
        'success': { class: 'btn-success', icon: 'bi-check-circle', text: '确认' }
    };
    
    const config = buttonConfig[type] || buttonConfig.primary;
    const modalId = 'confirmModal-' + Date.now();
    
    // 创建模态框HTML
    const modalHTML = `
        <div class="modal fade" id="${modalId}" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content border-0 shadow-lg">
                    <div class="modal-header border-0 pb-0">
                        <h5 class="modal-title fw-bold d-flex align-items-center">
                            <i class="bi ${config.icon} text-${type} me-2"></i>
                            ${title}
                        </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body pt-2">
                        <p class="mb-0">${message}</p>
                    </div>
                    <div class="modal-footer border-0 pt-0">
                        <button type="button" class="btn btn-light px-4" data-bs-dismiss="modal">
                            <i class="bi bi-x me-1"></i>取消
                        </button>
                        <button type="button" class="btn ${config.class} px-4" id="${modalId}-confirm">
                            <i class="bi ${config.icon} me-1"></i>${config.text}
                        </button>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // 添加到页面
    document.body.insertAdjacentHTML('beforeend', modalHTML);
    
    // 获取模态框元素
    const modalElement = document.getElementById(modalId);
    const confirmBtn = document.getElementById(modalId + '-confirm');
    
    // 绑定确认按钮事件
    confirmBtn.addEventListener('click', function() {
        const modal = bootstrap.Modal.getInstance(modalElement);
        modal.hide();
        if (onConfirm && typeof onConfirm === 'function') {
            onConfirm();
        }
    });
    
    // 绑定模态框隐藏后的清理事件
    modalElement.addEventListener('hidden.bs.modal', function() {
        modalElement.remove();
        if (onCancel && typeof onCancel === 'function') {
            onCancel();
        }
    });
    
    // 显示模态框
    const modal = new bootstrap.Modal(modalElement, {
        backdrop: 'static',
        keyboard: true
    });
    modal.show();
    
    // 聚焦到确认按钮
    modalElement.addEventListener('shown.bs.modal', function() {
        confirmBtn.focus();
    });
    
    return modal;
}

// 特殊的成功提示（带庆祝效果）
function showSuccessToast(title, message, duration = 6000) {
    console.log('🎉 显示成功提示:', title, message);
    
    // 创建Toast容器（如果不存在）
    let toastContainer = document.getElementById('toast-container');
    if (!toastContainer) {
        toastContainer = document.createElement('div');
        toastContainer.id = 'toast-container';
        toastContainer.className = 'toast-container position-fixed top-0 end-0 p-3';
        toastContainer.style.zIndex = '9999';
        document.body.appendChild(toastContainer);
    }
    
    const toastId = 'success-toast-' + Date.now();
    
    // 创建特殊的成功Toast
    const toastHTML = `
        <div id="${toastId}" class="toast border-0 shadow-lg" role="alert" aria-live="assertive" aria-atomic="true" data-bs-delay="${duration}" style="background: linear-gradient(135deg, #28a745 0%, #20c997 100%);">
            <div class="d-flex align-items-start text-white p-3">
                <div class="me-3">
                    <div class="success-icon-animated">
                        <i class="bi bi-check-circle-fill fs-3"></i>
                    </div>
                </div>
                <div class="flex-grow-1">
                    <div class="fw-bold mb-1">${title}</div>
                    <div class="small opacity-90">${message}</div>
                </div>
                <button type="button" class="btn-close btn-close-white ms-2" data-bs-dismiss="toast" aria-label="Close"></button>
            </div>
            <div class="toast-progress-bar"></div>
        </div>
    `;
    
    // 添加CSS动画样式
    if (!document.getElementById('success-toast-styles')) {
        const styles = document.createElement('style');
        styles.id = 'success-toast-styles';
        styles.textContent = `
            .success-icon-animated {
                animation: successBounce 0.6s ease-out;
            }
            
            @keyframes successBounce {
                0% { transform: scale(0.3) rotate(-15deg); opacity: 0; }
                50% { transform: scale(1.1) rotate(5deg); }
                100% { transform: scale(1) rotate(0deg); opacity: 1; }
            }
            
            .toast-progress-bar {
                height: 3px;
                background: rgba(255, 255, 255, 0.3);
                animation: progressBar ${duration}ms linear;
            }
            
            @keyframes progressBar {
                from { width: 100%; }
                to { width: 0%; }
            }
            
            .confetti {
                position: fixed;
                width: 10px;
                height: 10px;
                background: #ffd700;
                animation: confettiFall 3s ease-out forwards;
                pointer-events: none;
                z-index: 10000;
            }
            
            @keyframes confettiFall {
                0% {
                    transform: translateY(-100vh) rotate(0deg);
                    opacity: 1;
                }
                100% {
                    transform: translateY(100vh) rotate(720deg);
                    opacity: 0;
                }
            }
        `;
        document.head.appendChild(styles);
    }
    
    // 添加到容器
    toastContainer.insertAdjacentHTML('afterbegin', toastHTML);
    
    // 初始化并显示Toast
    const toastElement = document.getElementById(toastId);
    const toast = new bootstrap.Toast(toastElement, {
        animation: true,
        autohide: true,
        delay: duration
    });
    
    // 显示Toast
    toast.show();
    
    // 添加简单的庆祝效果
    createConfetti();
    
    // 自动移除DOM元素
    toastElement.addEventListener('hidden.bs.toast', function() {
        toastElement.remove();
        
        // 如果容器为空，也移除容器
        if (toastContainer.children.length === 0) {
            toastContainer.remove();
        }
    });
    
    return toast;
}

// 简单的庆祝效果
function createConfetti() {
    const colors = ['#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4', '#feca57', '#ff9ff3'];
    const confettiCount = 15;
    
    for (let i = 0; i < confettiCount; i++) {
        const confetti = document.createElement('div');
        confetti.className = 'confetti';
        confetti.style.left = Math.random() * 100 + 'vw';
        confetti.style.background = colors[Math.floor(Math.random() * colors.length)];
        confetti.style.animationDelay = (Math.random() * 2) + 's';
        confetti.style.animationDuration = (Math.random() * 2 + 2) + 's';
        
        document.body.appendChild(confetti);
        
        // 清理
        setTimeout(() => {
            confetti.remove();
        }, 4000);
    }
}

// 页面加载完成后的额外初始化
window.addEventListener('load', function() {
    console.log('🔧 题目设计页面完全加载完成');
    console.log('初始题目数组:', questions);
    
    // 更新调试信息
    const debugInfo = document.getElementById('debugInfo');
    if (debugInfo) {
        debugInfo.textContent = `已加载 ${questions.length} 题`;
    }
});
</script>
{% endblock %} 